import 'dart:async';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_sound/flutter_sound.dart' hide RecorderPlaybackController, SoundPlayerUI,SoundRecorderUI ;
import 'package:intl/date_symbol_data_local.dart';
import 'package:permission_handler/permission_handler.dart';

import 'package:studymanage/core/network_loading.dart';
import 'package:studymanage/core/sound/ui/demo_active_codec.dart';
import 'package:studymanage/core/sound/ui/recorder_playback_controller.dart';
import 'package:studymanage/core/sound/ui/recorder_state.dart';
import 'package:studymanage/core/sound/ui/sound_player_ui.dart';
import 'package:studymanage/core/sound/ui/sound_recorder_ui.dart';
import 'package:studymanage/core/sound/util/temp_file.dart';
import 'package:studymanage/util/request.dart';

class Share extends StatefulWidget {
  final Map<String,dynamic> detail;
  final String courseId;
  final setShare;

  Share(this.detail,this.courseId,this.setShare);

  @override
  State<StatefulWidget> createState() {
    return ShareState();
  }
}

class ShareState extends State<Share>{
  final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();

  String filepath=""; //录音本地路径
  String content=""; //分享内容
  String _audioPath;
  int _audioDuration = 1;
  double _currentSchedule = 0.0; // 进度条当前的值（0 ~ 1）
  Timer _timer; // 播放计时器
  bool initialized = false;
  Track track;


  @override
  void initState() {
    Future<PermissionStatus> status =  Permission.microphone.request();
    status.then((stat) {
      if (stat != PermissionStatus.granted) {
        throw RecordingPermissionException("Microphone permission not granted");
      }
    });
    tempFile(suffix: '.aac').then((path){
      filepath = path;
      track = Track(trackPath: filepath);
      setState(() {
      });
    });
    init();
    super.initState();
  }

  Future<bool> init()  async {
    if (!initialized) {
      initializeDateFormatting();
      await UtilRecorder().init();
      ActiveCodec().recorderModule = UtilRecorder().recorderModule;
      ActiveCodec().setCodec(withUI: false, codec: Codec.aacADTS);

      initialized = true;
    }
    return initialized;
  }

  @override
  void dispose() {
    if (filepath != null) {
      File(filepath).delete();
    }
    if(_timer!=null){
      _timer.cancel();
      _timer = null;
    }

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return NetworkLoading(
      child: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          brightness: Brightness.light,
          title: Text('分享',
            style: TextStyle(
              fontFamily: 'PingFangSC-Medium',
              fontSize: ScreenUtil().setSp(16),
              fontWeight: FontWeight.w600,
              color: Color.fromRGBO(51, 51, 51, 1),
              height: 1,
            ),
          ),
          centerTitle: true,
          backgroundColor: Colors.transparent,
          elevation: 0,
          leading: FlatButton(
            child: Icon(
              Icons.navigate_before,
              color: Color.fromRGBO(51, 51, 51, 1),
              size: ScreenUtil().setSp(30),
            ),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
          actions: <Widget>[
            Container(
              width: ScreenUtil().setWidth(90),
              child: FlatButton(
                padding: EdgeInsets.only(
                  left: ScreenUtil().setWidth(15.5),
                  right: ScreenUtil().setWidth(15.5),
                ),
                child: Text('确认提交',
                  style: TextStyle(
                    fontFamily: 'PingFangSC-Regular',
                    fontSize: ScreenUtil().setSp(13),
                    color: Color.fromRGBO(51, 51, 51, 1),
                    height: 1,
                  ),
                ),
                onPressed: () => _share(),
              ),
            ),
          ],
        ),
        body: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            // 触摸收起键盘
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: SingleChildScrollView(
            child: Form(
              key: _formKey,
                child: Container(
              width: MediaQuery.of(context).size.width,
              padding: EdgeInsets.only(
                left: ScreenUtil().setWidth(15),
                right: ScreenUtil().setWidth(15),
                top: ScreenUtil().setHeight(22),
              ),
              decoration: BoxDecoration(
                border: Border(
                  top: BorderSide(
                    color: Color.fromRGBO(248, 248, 248, 1),
                    width: ScreenUtil().setHeight(7.5),
                  ),
                ),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    widget.detail['taskTitle'],
                    style: TextStyle(
                      fontFamily: 'PingFangSC-Light',
                      fontSize: ScreenUtil().setSp(13),
                      fontWeight: FontWeight.w300,
                      color: Color.fromRGBO(133, 133, 133, 1),
                      height: 1,
                    ),
                    textAlign: TextAlign.justify,
                  ),
                  Container(
                    margin: EdgeInsets.only(
                      top: ScreenUtil().setHeight(13),
                    ),
                    child: Text(
                      widget.detail['courseName'],
                      style: TextStyle(
                        fontFamily: 'PingFangSC-Medium',
                        fontSize: ScreenUtil().setSp(15),
                        fontWeight: FontWeight.w600,
                        color: Color.fromRGBO(51, 51, 51, 1),
                        height: 1,
                      ),
                      textAlign: TextAlign.justify,
                    ),
                  ),
                  Container(
                    height: ScreenUtil().setHeight(142),
                    margin: EdgeInsets.only(
                      top: ScreenUtil().setHeight(20.5),
                    ),
                    padding: EdgeInsets.only(
                      left: ScreenUtil().setWidth(15.5),
                      right: ScreenUtil().setWidth(15.5),
                    ),
                    decoration: BoxDecoration(
                      color: Color.fromRGBO(248, 248, 248, 1),
                      borderRadius: BorderRadius.all(
                        Radius.circular(ScreenUtil().setHeight(4)),
                      ),
                    ),
                    child: TextFormField(
                      maxLines: 7,
                        inputFormatters:<TextInputFormatter>[
                          LengthLimitingTextInputFormatter(100)
                        ],
                      decoration: InputDecoration(
                        border: InputBorder.none,
                        hintText: '请输入课程内容（限100字）',
                        hintStyle: TextStyle(
                          fontFamily: 'PingFangSC-Light',
                          fontSize: ScreenUtil().setSp(13),
                          fontWeight: FontWeight.w300,
                          color: Color.fromRGBO(133, 133, 133, 1),
                        ),
                      ),
                        onSaved:(v){
                         setState(() {
                           content = v;
                         });
                        }
                    ),
                  ),
                  Offstage(
                    offstage: _audioPath == null,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Container(
                          height: ScreenUtil().setHeight(44),
                          margin: EdgeInsets.only(
                            top: ScreenUtil().setHeight(13),
                            bottom: ScreenUtil().setHeight(13),
                          ),
                          decoration: BoxDecoration(
                            border: Border.all(
                              color: Color.fromRGBO(214, 178, 128, 1),
                              width: ScreenUtil().setHeight(1),
                            ),
                            borderRadius: BorderRadius.all(
                              Radius.circular(ScreenUtil().setHeight(4)),
                            ),
                          ),
                          child: Center(),
                        ),
                        Container(
                          width: ScreenUtil().setWidth(44),
                          height: ScreenUtil().setHeight(44),
                          child: IconButton(
                            icon: ImageIcon(
                              AssetImage('assets/images/course/icon_delete.png'),
                              color: Color.fromRGBO(133, 133, 133, 1),
                            ),
                            onPressed: () {
                              showDialog(
                                context: context,
                                builder: (BuildContext context) {
                                  if (_timer == null) {
                                    return AlertDialog(
                                      contentPadding: EdgeInsets.all(0),
                                      actionsPadding: EdgeInsets.all(0),
                                      buttonPadding: EdgeInsets.all(0),
                                      insetPadding: EdgeInsets.all(0),
                                      content: Container(
                                        width: ScreenUtil().setWidth(300),
                                        decoration: BoxDecoration(
                                          border: Border(
                                            bottom: BorderSide(
                                              width: ScreenUtil().setHeight(0.5),
                                              color: Color.fromRGBO(238, 238, 238, 1),
                                            ),
                                          ),
                                        ),
                                        child: Row(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: <Widget>[
                                            Container(
                                              margin: EdgeInsets.only(
                                                top: ScreenUtil().setHeight(40.5),
                                                bottom: ScreenUtil().setHeight(32),
                                              ),
                                              child: Text('确定删除这段录音？',
                                                style: TextStyle(
                                                  fontFamily: 'PingFangSC-Regular',
                                                  fontSize: ScreenUtil().setSp(14),
                                                  color: Color.fromRGBO(25, 28, 34, 1),
                                                  height: 1,
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                      actions: <Widget>[
                                        Container(
                                          width: ScreenUtil().setWidth(150),
                                          height: ScreenUtil().setHeight(40),
                                          decoration: BoxDecoration(
                                            border: Border(
                                              right: BorderSide(
                                                width: ScreenUtil().setHeight(0.5),
                                                color: Color.fromRGBO(238, 238, 238, 1),
                                              ),
                                            ),
                                          ),
                                          child: FlatButton(
                                            child: Text('取消',
                                              style: TextStyle(
                                                fontFamily: 'PingFangSC-Medium',
                                                fontSize: ScreenUtil().setSp(14),
                                                fontWeight: FontWeight.w600,
                                                color: Color.fromRGBO(102, 102, 102, 1),
                                                height: 1,
                                              ),
                                            ),
                                            onPressed: () {
                                              Navigator.pop(context);
                                            },
                                          ),
                                        ),
                                        Container(
                                          width: ScreenUtil().setWidth(150),
                                          height: ScreenUtil().setHeight(40),
                                          child: FlatButton(
                                            child: Text('确认删除',
                                              style: TextStyle(
                                                fontFamily: 'PingFangSC-Medium',
                                                fontSize: ScreenUtil().setSp(14),
                                                fontWeight: FontWeight.w600,
                                                color: Color.fromRGBO(214, 178, 128, 1),
                                                height: 1,
                                              ),
                                            ),
                                            onPressed: () {
                                              setState(() {
                                                _audioPath = null;
                                                filepath = "";
                                              });

                                             Request().toast('删除成功');
                                              Navigator.pop(context);
                                            },
                                          ),
                                        ),
                                      ],
                                    );
                                  } else {
                                    return AlertDialog(
                                      contentPadding: EdgeInsets.all(0),
                                      actionsPadding: EdgeInsets.all(0),
                                      buttonPadding: EdgeInsets.all(0),
                                      insetPadding: EdgeInsets.all(0),
                                      content: Container(
                                        width: ScreenUtil().setWidth(300),
                                        decoration: BoxDecoration(
                                          border: Border(
                                            bottom: BorderSide(
                                              width: ScreenUtil().setHeight(0.5),
                                              color: Color.fromRGBO(238, 238, 238, 1),
                                            ),
                                          ),
                                        ),
                                        child: Row(
                                          mainAxisAlignment: MainAxisAlignment.center,
                                          children: <Widget>[
                                            Container(
                                              margin: EdgeInsets.only(
                                                top: ScreenUtil().setHeight(40.5),
                                                bottom: ScreenUtil().setHeight(32),
                                              ),
                                              child: Text('请暂停播放后再进行删除操作！',
                                                style: TextStyle(
                                                  fontFamily: 'PingFangSC-Regular',
                                                  fontSize: ScreenUtil().setSp(14),
                                                  color: Color.fromRGBO(25, 28, 34, 1),
                                                  height: 1,
                                                ),
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                      actions: <Widget>[
                                        Container(
                                          width: ScreenUtil().setWidth(300),
                                          height: ScreenUtil().setHeight(40),
                                          child: FlatButton(
                                            child: Text('确认',
                                              style: TextStyle(
                                                fontFamily: 'PingFangSC-Medium',
                                                fontSize: ScreenUtil().setSp(14),
                                                fontWeight: FontWeight.w600,
                                                color: Color.fromRGBO(102, 102, 102, 1),
                                                height: 1,
                                              ),
                                            ),
                                            onPressed: () {
                                              Navigator.pop(context);
                                            },
                                          ),
                                        ),
                                      ],
                                    );
                                  }
                                },
                              );
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                  FutureBuilder(
                    initialData: false,
                    future: init(),
                    builder: (c,d){
                      if (d.data == false) {
                        return Container(
                          width: 0,
                          height: 0,
                          color: Colors.white,
                        );
                      } else {
                        return RecorderPlaybackController(
                            child: Column(
                              children: [
                                Container(
                                  margin: EdgeInsets.only(
                                    bottom: ScreenUtil().setHeight(10),
                                  ),
                                  decoration: BoxDecoration(
                                    border: Border.all(
                                      color: Color.fromRGBO(214, 178, 128, 1),
                                      width: ScreenUtil().setHeight(1),
                                    ),
                                    borderRadius: BorderRadius.all(
                                      Radius.circular(5),
                                    ),
                                  ),
                                  child: SoundPlayerUI.fromTrack(
                                    track,
                                    type: 1,
                                    backgroundColor: Colors.white,
                                    enabled: false,
                                    showTitle: true,
                                    audioFocus: true
                                        ? AudioFocus.requestFocusAndDuckOthers
                                        : AudioFocus.requestFocusAndDuckOthers,
                                  ),
                                ),
                                SoundRecorderUI(
                                  track,
                                ),
                              ],
                            ));
                      }
                    },
                  )
                ],
              ),
            )
            ),
          ),
        ),
      ),
    );
  }

  _share() async{
    print('确认提交');
    _formKey.currentState.save();
    if(content.isEmpty){
      Request().toast("请填写内容");
      return;
    }
    if(filepath.isNotEmpty){
      Upload().upload("/multiapi/open/upload",
          FormData.fromMap({
            "file": await MultipartFile.fromFile(filepath)
          })).then((response){
        Request().post<Map<String,dynamic>>("/multiapi/c194c_studyRecordShare",
            data:{
              "taskId":  widget.detail['taskId'],
              "courseId":widget.courseId,
              "shareRecordContent":content,
              "shareRecordContentVoice":response.data['url'],
              "shareVoiceAudioDuration":_audioDuration
            }).then((response){
              if(response.code == 200){
                widget.setShare();
                Navigator.pop(context);
              }
        });
      });
    }else{
      Request().post<Map<String,dynamic>>("/multiapi/c194c_studyRecordShare",
          data: {
            "taskId":  widget.detail['taskId'],
            "courseId":widget.courseId,
            "shareRecordContent":content,
            "shareRecordContentVoice":"",
            "shareVoiceAudioDuration":0
          }).then((response){
        if(response.code == 200){
          widget.setShare();
          Navigator.pop(context);
          Request().toast('分享成功');
        }
      });
    }
  }

  _left() {
    if(_currentSchedule < 1){
      return ScreenUtil().setWidth(155) * _currentSchedule;
    }else{
      return ScreenUtil().setWidth(165);
    }
  }
}